using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using cframework;
using Newtonsoft.Json;

namespace cframework
{
    [EssentialTools("WECHAT_DEVTOOL_CLI", "https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html")]
    [CreateAssetMenu(menuName = "cframework/ChannelUtil_Wx")]
    public class ChannelUtil_Wx : ChannelUtil
    {
        // [Title("微信小游戏")]


        public override bool Deploy(BuildPlayerSetting bps, string projectPath, string destPath, string paramStr, ref string downloadUrl)
        {
            downloadUrl = null;
            var cliPath = bps.deviceToolPaths.GetToolPath("WECHAT_DEVTOOL_CLI");

            var param = $"upload --project {projectPath} {paramStr}";
            var workDir = System.IO.Path.GetDirectoryName(Application.dataPath);

            Debug.Log($"{workDir} => {cliPath} {param}");

            var ret = CommandLineTool.RunCommand2(cliPath, param, workDir);
            if (ret.ExitCode != 0)
            {
                Debug.LogError("output: " + ret.StdOut);
                Debug.LogError("error: " + ret.StdErr);

                return false;
            }
            else
            {
                var param2 = $"preview --project {projectPath}";
                Debug.Log($"{workDir} => {cliPath} {param2}");

                var ret2 = CommandLineTool.RunCommand2(cliPath, param2, workDir);
                if (ret2.ExitCode != 0)
                {
                    Debug.LogError("output: " + ret2.StdOut);
                    Debug.LogError("error: " + ret2.StdErr);

                    return false;
                }
                else
                {
                    string projectConfigJsonPath = projectPath + "/project.config.json";
                    string str = System.IO.File.ReadAllText(projectConfigJsonPath);

                    var a = JsonConvert.DeserializeObject<Dictionary<string, object>>(str);
                    string appid = a["appid"].ToString();

                    downloadUrl = $"https://open.weixin.qq.com/sns/getexpappinfo?appid={appid}#wechat-redirect";
                }
            }

            return true;
        }
    }
}